package com.hqx.gulimall.product.service.impl;

import com.hqx.common.to.SkuReductionTo;
import com.hqx.common.to.SpuBoundTo;
import com.hqx.common.utils.R;
import com.hqx.gulimall.product.entity.*;
import com.hqx.gulimall.product.feign.CouponFeignService;
import com.hqx.gulimall.product.service.*;
import com.hqx.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqx.common.utils.PageUtils;
import com.hqx.common.utils.Query;

import com.hqx.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private SpuImagesService spuImagesService;

    @Resource
    private AttrService attrService;

    @Resource
    private ProductAttrValueService productAttrValueService;

    @Resource
    private SkuInfoService skuInfoService;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String status = (String) params.get("status");
        String key = (String) params.get("key");
        if(StringUtils.hasText(catelogId) && Integer.parseInt(catelogId) != 0)
            queryWrapper.eq("catalog_id",catelogId);
        if(StringUtils.hasText(brandId) && Integer.parseInt(brandId) != 0)
            queryWrapper.eq("brand_id",brandId);
        if(StringUtils.hasText(status))
            queryWrapper.eq("publish_status",status);
        if(StringUtils.hasText(key))
            queryWrapper.and(obj -> obj.eq("id",key).or().like("spu_name",key));

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    /**
     *1：保存spu基本信息  SpuInfoEntity  pms_spu_info
     * 2：保存spu描述图片 SpuInfoDescEntity  pms_spu_info_desc
     * 3：保存spu图片集 SpuImagesEntity  pms_spu_images
     * 4：保存spu积分信息  sms_spu_bounds
     * 5：保存spu规格参数(基本属性)  pms_product_attr_value
     * 6：保存spu对应的sku信息
     *       61：保存sku基本信息  pms_sku_info
     *       6.2：保存sku图片信息  pms_sku_images
     *       63：保存sku销售属性  pms_sku_sale_attr_value
     *       6.4：保存sku的优惠、满减等信息  sms_sku_ladder  sms_sku_full_reduction  sms_member__price
     */
    @Override
    @Transactional
    public void saveInfo(SpuSaveVo spuInfo) {
        // 保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        // 保存spu描述图片
        List<String> desc = spuInfo.getDecript();
        if(!desc.isEmpty()) {
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
            spuInfoDescEntity.setDecript(String.join(",", desc));
            spuInfoDescService.save(spuInfoDescEntity);
        }

        // 保存spu图片集
        List<String> images =spuInfo.getImages();
        if(!images.isEmpty()) {
            List<SpuImagesEntity> spuImagesEntityList = images.stream().map(image -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(image);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(spuImagesEntityList);
        }

        // 保存spu规格参数(基本属性)
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        if(!baseAttrs.isEmpty()){
            List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(baseAttr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                productAttrValueEntity.setAttrId(baseAttr.getAttrId());
                AttrEntity attrEntity = attrService.getById(baseAttr.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
                productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveProductAttr(productAttrValueEntityList);
        }

        // 保存spu的积分信息
        Bounds bounds = spuInfo.getBounds();
        if(bounds != null){
            SpuBoundTo spuBoundTo = new SpuBoundTo();
            BeanUtils.copyProperties(bounds,spuBoundTo);
            spuBoundTo.setSpuId(spuInfoEntity.getId());
            R r = couponFeignService.saveSpuBounds(spuBoundTo);
            if(r.getCode() != 0)
                log.error("远程保存spu积分信息失败");
        }

        // 保存spu对应的sku信息
        List<Skus> skus = spuInfo.getSkus();
        if(!skus.isEmpty()){
            skus.forEach(sku -> {
                // sku基本信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                String defaultImage = "";
                if(!sku.getImages().isEmpty()) {
                    for (Images image : sku.getImages()) {
                        if (image.getDefaultImg() == 1) {
                            defaultImage = image.getImgUrl();
                            break;
                        }
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                // sku图片信息
                List<Images> skuImages =  sku.getImages();
                if(!skuImages.isEmpty()){
                    List<SkuImagesEntity> skuImagesEntityList = skuImages.stream().map(skuImage -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        BeanUtils.copyProperties(skuImage,skuImagesEntity);
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuImagesEntity;
                    }).filter(entity -> StringUtils.hasText(entity.getImgUrl())).collect(Collectors.toList());
                    skuImagesService.saveBatch(skuImagesEntityList);
                }

                // sku销售属性
                List<Attr> attrs = sku.getAttr();
                if(!attrs.isEmpty()){
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrs.stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
                }

                // sku的优惠、满减等信息
                if(sku.getFullCount() > 0 || sku.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                    SkuReductionTo skuReductionTo = new SkuReductionTo();
                    BeanUtils.copyProperties(sku, skuReductionTo);
                    skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0)
                        log.error("远程保存sku优惠信息失败");
                }
            });
        }

    }

}